package com.fyt.ZhongYaoApp.service.impl;

//import com.fyt.ZhongYaoApp.config.SecurityConfig;
import com.fyt.ZhongYaoApp.mapper.UserMapper;
import com.fyt.ZhongYaoApp.pojo.User;
import com.fyt.ZhongYaoApp.service.UserService;
import com.fyt.ZhongYaoApp.utils.Md5Util;
import com.fyt.ZhongYaoApp.utils.ThreadLocalUtil;
import com.fyt.ZhongYaoApp.utils.UidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

//    @Autowired
//    private PasswordEncoder passwordEncoder;

    @Override
    public User findByID(int id)
    {
        return userMapper.selectUserById(id);
    }

    @Override
    public User findByUserName(String username) {
        User u = userMapper.findByUserName(username);
        System.out.println(username);
        return u;
    }

    /**
     * 用户注册
     * @param username
     * @param password
     */
    @Override
    public void register(String username, String password) {
        // 加密
        String md5String = Md5Util.getMD5String(password);
//        String encode = passwordEncoder.encode(password);

        // 唯一id生成
        UidUtil uidUtil = new UidUtil(0,0);
        long luId = uidUtil.nextId();
        String uId = String.valueOf(luId).substring(String.valueOf(luId).length() - 8);

        // 添加
        userMapper.add(username,md5String,uId);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        System.out.println(user.getUpdateTime());
        userMapper.update(user);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer)map.get("id");
        userMapper.updatePwd(Md5Util.getMD5String(newPwd),id);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        // 获得请求头，解析后获得id
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = (Integer)map.get("id");
        userMapper.updateAvatar(avatarUrl,id);
    }
}
